<!-- 发布文章 -->
<template>
  <!-- <div class="div_form"> -->
  <el-form
    ref="form"
    :model="form"
    label-width="80px"
    style="background-color: white; padding: 30px 60px; border-radius: 6px"
  >
    <el-input
      class="div_form_margin"
      v-model="form.inputTitle"
      placeholder=" 标 题 "
    ></el-input>

    <el-input
      class="div_form_margin"
      type="textarea"
      :autosize="{ minRows: 2, maxRows: 4 }"
      placeholder=" 摘 要 "
      v-model="form.inputOutline"
    ></el-input>

    <quill-editor
      ref="quillEditor"
      v-model="form.content"
      class="myQuillEditor div_form_margin"
      :options="editorOption"
      @change="onEditorChange($event)"
    />
    <el-upload
      class="avatar-upload"
      action="http://gulimall-yangrong.oss-cn-shanghai.aliyuncs.com"
      list-type="picture-card"
      ref="editorUploadImage"
      :data="avatarDataObj"
      :before-upload="avatarBeforeUpload"
      :on-success="avatarUploadSuccess"
      :style="{ display: 'none' }"
      :on-error="avatarUploadError"
      :on-remove="handleRemove"
      accept=".jpg, .jpeg, .png, .gif, .JPG, .JPEG, .GIF, .PNG"
    ></el-upload>

    <el-form-item label="展示封面" style="height: 148px">
      <el-upload
        action="http://gulimall-yangrong.oss-cn-shanghai.aliyuncs.com"
        list-type="picture-card"
        ref="uploadImage"
        :data="dataObj"
        :before-upload="beforeUpload"
        :on-success="handleUploadSuccess"
        :auto-upload="false"
        :on-preview="handlePictureCardPreview"
        :limit="1"
        :on-change="handleChange"
        :on-remove="handleRemove"
        accept=".jpg, .jpeg, .png, .gif, .JPG, .JPEG, .GIF, .PNG"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>

      <div style="margin-left: 20px; font-size: 16px">
        优质的封面有利于推荐上首页以及置顶，格式支持JPEG、PNG、GIF封面图最佳尺寸：900px
        x 446px 、分辨率72dpi、文件大小不超过1M
        图片要求：清晰，不包含敏感信息，表达紧贴文章主题
      </div>

      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt />
      </el-dialog>
    </el-form-item>

    <el-form-item label="添加标签">
      <el-select
        class="max_width_select"
        v-model="articleLabelValue"
        multiple
        filterable
        placeholder="请选择文章标签"
        @change="labelChange"
      >
        <el-option
          v-for="item in articleLabelOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="文章分类">
      <el-select
        class="max_width_select"
        v-model="form.articleTypeValue"
        placeholder="请选择文章分类"
      >
        <el-option
          v-for="item in articleTypeOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="申请推荐">
      <el-checkbox v-model="form.applyForHomepage">申请上首页</el-checkbox>
      <el-tooltip
        class="item"
        effect="dark"
        content="如需沟通上首页、投放广告相关事宜，请发送邮件至：xxxxx@qq.com"
        placement="right"
        style="margin-left: 10px"
      >
        <el-button type="text" icon="el-icon-question" circle></el-button>
      </el-tooltip>
    </el-form-item>

    <el-form-item label="版权声明">
      <div
        style="
          background-color: #ccc;
          border-radius: 6px;
          padding: 0 20px;
          width: 100%;
        "
      >
        <p style="display: flex">
          作者：
          <span v-if="copyrightEdit">{{ form.copyrightAuthor }}</span>
          <el-input
            size="mini"
            v-model="form.copyrightAuthor"
            placeholder="请输入内容"
            maxlength="20"
            clearable
            style="width: 300px"
            v-if="copyrightSave"
          ></el-input>
        </p>
        <p>如需转载，请标明来源及链接。</p>
        <p>
          XXX作为资讯平台，仅为展示和提供相关信息，文章不构成任何投资建议。如发现文章含敏感或不当信息，欢迎致信hello@qq.com举报。
        </p>
        <p>
          图片来源：
          <span v-if="copyrightEdit">{{ form.copyrightImageAuthor }}</span>
          <el-input
            size="mini"
            v-model="form.copyrightImageAuthor"
            placeholder="请输入内容"
            maxlength="20"
            clearable
            style="width: 300px"
            v-if="copyrightSave"
          ></el-input
          >&nbsp;如有侵权，请联系作者删除。
        </p>
      </div>
    </el-form-item>

    <el-form-item class="copyright-edit-button">
      <el-button v-if="copyrightEdit" @click="checkCopyrightEdit" round
        >编辑</el-button
      >
      <el-button v-if="copyrightSave" @click="checkCopyrightSave" round
        >保存</el-button
      >
    </el-form-item>

    <el-divider></el-divider>
    <el-form-item class="copyright-edit-button">
      <span style="font-size: 16px; margin-right: 60px"
        >正文字数：{{ editorLength }}/10000</span
      >
      <el-button type="primary" @click="submit">
        提交
        <i class="el-icon-check el-icon--right"></i>
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { policy } from "@/components/upload/policy";
import { getUUID } from "@/utils";

import { quillEditor } from "vue-quill-editor"; //调用编辑器

import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

import "@/assets/css/vue-quill-editor-style.css";

import * as Quill from "quill";
let fontSizeStyle = Quill.import("attributors/style/size");
fontSizeStyle.whitelist = [
  "10px",
  "12px",
  "14px",
  "16px",
  "20px",
  "24px",
  "36px",
]; //false表示默认值
Quill.register(fontSizeStyle, true);

// quill文本编辑器工具栏提示
const titleConfig = {
  "ql-bold": "加粗",
  "ql-color": "颜色",
  "ql-font": "字体",
  "ql-code": "插入代码",
  "ql-italic": "斜体",
  "ql-link": "添加链接",
  "ql-background": "背景颜色",
  "ql-size": "字体大小",
  "ql-strike": "删除线",
  "ql-script": "上标/下标",
  "ql-underline": "下划线",
  "ql-blockquote": "引用",
  "ql-header": "标题",
  "ql-indent": "缩进",
  "ql-list": "列表",
  "ql-align": "文本对齐",
  "ql-direction": "文本方向",
  "ql-code-block": "代码块",
  "ql-formula": "公式",
  "ql-image": "图片",
  "ql-clean": "清除字体样式",
};
// quill文本编辑器工具栏
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
  ["blockquote", "code-block"], // 引用  代码块
  [{ header: 1 }, { header: 2 }], // 1、2 级标题
  [{ list: "ordered" }], // 有序、无序列表
  [{ script: "sub" }, { script: "super" }], // 上标/下标
  [{ indent: "-1" }, { indent: "+1" }], // 缩进
  [{ direction: "rtl" }], // 文本方向
  [{ color: [] }],
  [{ background: [] }], // {  color: [] }, 字体颜色、字体背景颜色
  [{ font: [] }], // 字体种类
  [{ align: [] }], // 对齐方式
  ["clean"], // 清除文本格式
  ["link", "image"], // , 链接、图片、视频
];

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    quillEditor,
    Quill,
  },
  data() {
    //这里存放数据
    return {
      form: {
        imageUrl: "",
        inputTitle: "",
        inputOutline: "",
        content: "",
        articleLabelValue: "",
        articleTypeValue: "",
        applyForHomepage: false,
        copyrightAuthor: "版权作者",
        copyrightImageAuthor: "图片版权归属人",
      },
      avatarDataObj: {
        policy: "",
        signature: "",
        key: "",
        ossaccessKeyId: "",
        dir: "",
        host: "",
      },
      dataObj: {
        policy: "",
        signature: "",
        key: "",
        ossaccessKeyId: "",
        dir: "",
        host: "",
        // callback:'',
      },
      imageUrl: "",
      userInfo: {},
      avatarImageUrl: "",
      avatarImageUrlList: [],
      articleLabelOptions: [],
      articleTypeOptions: [],
      articleLabelValue: [],
      labelPosition: "right",
      dialogImageUrl: "",
      dialogVisible: false,
      copyrightEdit: true,
      copyrightSave: false,
      editorLength: 0,
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              // 替换文本编辑器的图片上传，改为使用<el-upload>进行上传
              image: function (value) {
                if (value) {
                  document.querySelector(".avatar-upload input").click();
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
        },
      },
    };
  },
  //监听属性 类似于data概念
  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill;
    },
  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    submit() {
      this.$refs.uploadImage.submit();
    },

    // ========================富文本编辑器========================
    onEditorReady(editor) {}, // 准备编辑器
    onEditorBlur() {}, // 失去焦点事件
    onEditorFocus() {}, // 获得焦点事件
    // 内容改变事件
    onEditorChange(event) {
      event.quill.deleteText(10000, 4);
      if (this.content === "") {
        this.editorLength = 0;
      } else {
        this.editorLength = event.quill.getLength() - 1;
      }
    },
    // 工具栏中文提示
    addQuillTitle() {
      const oToolBar = document.querySelector(".ql-toolbar"),
        aButton = oToolBar.querySelectorAll("button"),
        aSelect = oToolBar.querySelectorAll("select");
      aButton.forEach(function (item) {
        if (item.className === "ql-script") {
          item.value === "sub" ? (item.title = "下标") : (item.title = "上标");
        } else if (item.className === "ql-indent") {
          item.value === "+1"
            ? (item.title = "向右缩进")
            : (item.title = "向左缩进");
        } else {
          item.title = titleConfig[item.classList[0]];
        }
      });
      aSelect.forEach(function (item) {
        item.parentNode.title = titleConfig[item.classList[0]];
      });
    },
    // 图片上传
    avatarBeforeUpload(file) {
      let _self = this;
      _self.avatarImageUrl = "";
      return new Promise((resolve, reject) => {
        policy()
          .then((response) => {
            _self.avatarDataObj.policy = response.data.policy;
            _self.avatarDataObj.signature = response.data.signature;
            _self.avatarDataObj.ossaccessKeyId = response.data.accessid;
            _self.avatarDataObj.key =
              response.data.dir +
              getUUID() +
              "." +
              file.type.substring(file.type.lastIndexOf("/") + 1);
            _self.avatarDataObj.dir = response.data.dir;
            _self.avatarDataObj.host = response.data.host;
            _self.avatarImageUrl =
              _self.avatarDataObj.host + "/" + _self.avatarDataObj.key;
            this.avatarImageUrlList.push(_self.avatarDataObj.key);
            resolve(true);
          })
          .catch((err) => {
            reject(false);
          });
      });
    },
    avatarUploadSuccess(res, file) {
      // 首先获取富文本编辑器的实例
      let quill = this.$refs.quillEditor.quill;
      // 上传成功所执行
      if (this.avatarImageUrl != "") {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片res为服务器返回的数据
        quill.insertEmbed(length, "image", this.avatarImageUrl);
        // 光标移动至文本末端
        quill.setSelection(length + 1);
      } else {
        this.$message.error("图片插入失败");
      }
      // loading动画消失
      this.quillUpdateImg = false;
    },
    avatarUploadError() {
      // loading动画消失
      this.quillUpdateImg = false;
      this.$message.error("图片插入失败");
    },
    // ===========================================================

    // ========================封面图片上传========================
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleChange(file, fileList) {
      // 限制上传1张封面图片，添加1张图片胡隐藏添加区域
      this.$refs.uploadImage.$children[1].$el.style.display = "none";
    },
    handleRemove(file, fileList) {
      // 限制上传1张封面图片，移除已添加的图片时，恢复添加区域显示状态
      this.$refs.uploadImage.$children[1].$el.style.display = "inline-block";
    },
    beforeUpload(file) {
      let _self = this;
      return new Promise((resolve, reject) => {
        policy()
          .then((response) => {
            _self.dataObj.policy = response.data.policy;
            _self.dataObj.signature = response.data.signature;
            _self.dataObj.ossaccessKeyId = response.data.accessid;
            _self.dataObj.key =
              response.data.dir +
              getUUID() +
              "." +
              file.type.substring(file.type.lastIndexOf("/") + 1);
            _self.dataObj.dir = response.data.dir;
            _self.dataObj.host = response.data.host;
            _self.form.imageUrl = _self.dataObj.host + "/" + _self.dataObj.key;
            resolve(true);
          })
          .catch((err) => {
            reject(false);
          });
      });
    },
    handleUploadSuccess(res, file, fileList) {
      // 文章封面图上传成功后进行文章保存操作，否则无法取到封面图远程链接
      this.$http({
        url: this.$http.adornUrl("/article/tbarticles/save"),
        method: "post",
        data: this.$http.adornData(
          {
            title: this.form.inputTitle,
            image: this.form.imageUrl,
            userName: this.userInfo.username,
            copyrightAuthor: this.form.copyrightAuthor,
            copyrightImageAuthor: this.form.copyrightImageAuthor,
            label: this.form.articleLabelValue,
            type: this.form.articleTypeValue,
            outline: this.form.inputOutline,
            content: this.form.content,
            avatarImageList: this.avatarImageUrlList,
          },
          false
        ),
      }).then(({ data }) => {
        if (data.code == 0) {
          this.$message({
            message: "文章提交成功！",
            type: "success",
          });
        }
      });
    },
    // ===========================================================

    // ========================版权声明区域========================
    checkCopyrightEdit() {
      this.copyrightEdit = false;
      this.copyrightSave = true;
    },
    checkCopyrightSave() {
      this.copyrightEdit = true;
      this.copyrightSave = false;
    },
    // ===========================================================

    // ========================文章标签区域========================
    getArticleLabel() {
      this.$http({
        url: this.$http.adornUrl("/article/tbarticlelabel/getAllLabelList"),
        method: "get",
      }).then(({ data }) => {
        this.articleLabelOptions = data.labelList;
      });
    },
    labelChange(value) {
      let str = "";

      for (let index = 0; index < this.articleLabelValue.length; index++) {
        str = str + "|" + this.articleLabelValue[index];
        if (index == this.articleLabelValue.length - 1) {
          str = str + "|";
        }
      }
      this.form.articleLabelValue = str;
    },
    // ===========================================================

    // ========================文章类型区域========================
    getArticleType() {
      this.$http({
        url: this.$http.adornUrl("/article/tbarticletype/getAllTypeList"),
        method: "get",
      }).then(({ data }) => {
        this.articleTypeOptions = data.typeList;
      });
    },
    // ===========================================================
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getArticleLabel();
    this.getArticleType();
    this.addQuillTitle();
    // 判断用户数据是否存在
    var userJsonStr = sessionStorage.getItem("user");
    if (userJsonStr != null) {
      _this.userInfo = JSON.parse(userJsonStr);
    }
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped>
.div_form_margin {
  margin-bottom: 20px;
}

.max_width_select {
  width: 100%;
}
</style>

<style>
.quill-editor {
  background-color: white;
}

.ql-container {
  height: 400px;
}

.ql-toolbar.ql-snow {
  text-align: left;
  background-color: white;
}

.copyright-edit-button .el-form-item__content {
  float: right;
}
</style>

<style>
.el-form-item__content {
  display: flex;
}

.ql-toolbar.ql-snow {
  border-top-left-radius: 6px;
  border-top-right-radius: 6px;
}

.ql-container.ql-snow {
  border-bottom-left-radius: 6px;
  border-bottom-right-radius: 6px;
}
</style>